package net.yxsoft.service.infrastructure;

import com.jfinal.aop.Before;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.utils.JsonUtils;

import net.yxsoft.enumclass.StateEnumCls;
import net.yxsoft.kit.AESKit;
import net.yxsoft.kit.Helper;
import net.yxsoft.kit.HttpKit;
import net.yxsoft.model.infrastructure.TsCode;
import net.yxsoft.resource.DbSourceRes;
import net.yxsoft.service.common.BaseService;
import rapid.core.Authuser;
import rapid.core.ContextStateEnum;
import rapid.core.TResult;
import rapid.util.StrKit;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mlb on 2016/5/12.
 */
public class CodeService extends BaseService {

  public static final CodeService INSTANCE = new CodeService();

  public static final int codeIdLength = 3;  //生成编号每级的位数

  private final TsCode tsCodeDao = new TsCode().dao();


  /**
   * @MethodName: addCode
   * @Description:新增数据字典信息
   * @param: model
   * @param: user
   * @return * @return rapid.core.TResult
   * @throws
   * @date 2023/8/31 12:33
   * @author wj
   */
  public TResult addCode(TsCode model, Authuser user) {

    TResult _result = new TResult();

    if(model == null) {
      _result.setState(ContextStateEnum.FAIL);
      _result.setMessage("保存数据异常。");
      return _result;
    }



    Timestamp time = new Timestamp(new java.util.Date().getTime());
    StringBuilder _strLeaf = new StringBuilder();
    StringBuilder _strParentId = new StringBuilder();
    StringBuilder _strCodeType = new StringBuilder();
    StringBuilder _strRootcustomid = new StringBuilder();
    String _codeId = getCodeId(model.getParentid(), _strLeaf, _strParentId, _strCodeType,_strRootcustomid,model.getCustomid());
    String _customid = model.getCustomid();
    TsCode _exsitName = TsCode.dao.findFirst("SELECT * FROM TS_CODE \n" +
                                               " WHERE ((CUSTOMID =? OR CODENAME=?) AND LEAF = '0') OR \n" +
                                               " (( CUSTOMID =? OR (CODENAME =? AND PARENTCUSTOMID =?)) AND CODETYPE =?) OR \n" +
                                               " (LEAF='1' AND CUSTOMID=? )",
                                             _customid, model.getCodename(),_customid, model.getCodename(), model.getParentcustomid(),
                                             _strCodeType.toString(),_customid);
    TsCode  _parentCode=TsCode.dao.findFirst("SELECT * FROM TS_CODE WHERE CODEID=?",model.getParentid());
    if(com.jfinal.kit.StrKit.notNull(_parentCode)){
      model.setParentcustomid(_parentCode.getCustomid());
    }

    if(_exsitName != null) {
      if(model.getParentcustomid()==null && _exsitName.getParentcustomid()==null && _strLeaf.toString().equals(_exsitName.getLeaf()))      {
        if(_exsitName.getCodename().equals(model.getCodename())) {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下名称已经存在。");
        } else {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下自定义编号已经存在。");
        }
      }else if(_strLeaf.toString().equals(_exsitName.getLeaf()) && model.getParentcustomid().equals(_exsitName.getParentcustomid())) {
        if(_exsitName.getCodename().equals(model.getCodename())) {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下名称已经存在。");
        } else {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下自定义编号已经存在。");
        }
      } else if("1".equals(_exsitName.getLeaf())) {
        _result.setState(ContextStateEnum.FAIL);
        _result.setMessage("自定义编号不能与1级节点相同。");
      } else if("0".equals(_exsitName.getLeaf())) {
        _result.setState(ContextStateEnum.FAIL);
        _result.setMessage("自定义编号不能与根节点相同。");
      } else {
        _result.setState(ContextStateEnum.FAIL);
        _result.setMessage("当前1级节点下自定义编号已经存在。");
      }
      return _result;
    }
    model.setCodeid(_codeId);
    model.setEnabled(StateEnumCls.ENABLED.getValue().toString());
    model.setCreated(time);
    model.setLeaf(_strLeaf.toString());
    model.setParentid(_strParentId.toString());
    model.setCodeType(_strCodeType.toString());
    model.setRootcustomid(_strRootcustomid.toString());
    if("null".equals(model.getIcon())){
      model.setIcon("");
    }
    model.setId(Helper.bulidUUID());
    boolean _r = model.save();

    if(_r) {
      _result.setState(ContextStateEnum.SUCCESS);
      log(user.getLoginId(), user.getName(), "系统管理/数据词典", "新增", user.getIp(), "主键：" + model.getId() + "，名称：" + model.getCodename() + "，编号：" + model.getCodeid());
      _result.setMessage("保存成功。");
      return _result;
    } else {
      _result.setState(ContextStateEnum.FAIL);
      _result.setMessage("保存失败。");
      return _result;
    }
  }

  /**
  * @MethodName: getCodeId
  * @Description: 获取新的编号
  * @param: parentId
   * @param: leaf
   * @param: defParentId
   * @param: codeType
   * @param: rootcustomid
   * @param: customid
  * @return * @return java.lang.String
  * @throws
  * @date 2023/8/31 12:35
  * @author wj
  */
  public String getCodeId(String parentId, StringBuilder leaf, StringBuilder defParentId, StringBuilder codeType,StringBuilder rootcustomid,String customid) {
    String _returnStr = "";

    if(parentId == null || parentId == "" || parentId == "0") {
      //说明是顶级

      //取最大编号
      String _maxCode = Db.queryStr("SELECT MAX(CODEID) FROM TS_CODE WHERE LEAF = 0");

      if(com.jfinal.kit.StrKit.isBlank(_maxCode)) {
        //第一次生成编号
        _returnStr = assembleCodeId();
      } else {
        //最大编号加一
        String _t = (Integer.parseInt(_maxCode) + 1) + "";
        _returnStr = assembleCodeId(_t);
      }

      leaf.append("0");//0标志位顶级
      defParentId.append("0");

    } else {

      //不是顶级，就要生成子集编号，需要加上父级编号前缀
      String _maxCode = Db.queryStr("SELECT MAX(CODEID) FROM TS_CODE WHERE PARENTID =?", parentId);
      if(com.jfinal.kit.StrKit.isBlank(_maxCode)) {
        _returnStr = parentId + assembleCodeId();
      } else {
        String _cCode = _maxCode.substring(parentId.length(), parentId.length() + codeIdLength);
        String _t = (Integer.parseInt(_cCode) + 1) + "";
        _returnStr = parentId + assembleCodeId(_t);
      }
      TsCode model = TsCode.dao.findFirst("SELECT * FROM TS_CODE WHERE CODEID =?",parentId); //父级
      if(model!=null) {
        String _l=model.getLeaf();
        if(com.jfinal.kit.StrKit.notBlank(_l)) {
          leaf.append((Integer.parseInt(_l) + 1) + "");//1标志为子集
        }else {
          leaf.append("1");
        }
        String _c = model.getCodeType();
        if("1".equals(leaf.toString())){
          _c=customid;
        }else if(com.jfinal.kit.StrKit.isBlank(_c) || "".equals(_c) || _l.equals("1")){
          _c = model.getCustomid();
        }
        codeType.append(_c);
        String _t = model.getRootcustomid();
        if(StrKit.isBlank(_t) || "".equals(_t)) {
          _t = model.getCustomid();
        }
        rootcustomid.append(_t);
      }
      defParentId.append(parentId);
    }
    return _returnStr;
  }

  /**
  * @MethodName: assembleCodeId
  * @Description: 根据预先设定编号长度，生成编号（有参）
  * @param: maxCode 最大编号
  * @return * @return java.lang.String
  * @throws
  * @date 2023/8/31 12:36
  * @author wj
  */
  public String assembleCodeId(String maxCode) {
    int _maxcodelength = maxCode.length();
    String _returnstr = "";
    for(int i = 0; i < codeIdLength - _maxcodelength; i++) {
      _returnstr += "0";
    }
    return _returnstr + maxCode;
  }

  /**
  * @MethodName: assembleCodeId
  * @Description: 根据预先设定编号长度，生成编号（无参）
  * @param:
  * @return * @return java.lang.String
  * @throws
  * @date 2023/8/31 12:36
  * @author wj
  */
  public String assembleCodeId() {
    String _returnstr = "";
    for(int i = 0; i < codeIdLength - 1; i++) {
      _returnstr += "0";
    }
    return _returnstr + "1";
  }


/**
* @MethodName: updateCode
* @Description: 修改数据字典信息
* @param: model
 * @param: user
* @return * @return rapid.core.TResult
* @throws
* @date 2023/8/31 12:37
* @author wj
*/
  @Before(Tx.class)
  public TResult updateCode(TsCode model,Authuser user ) {

    TResult _result = new TResult();

    if(model == null) {
      _result.setState(ContextStateEnum.FAIL);
      _result.setMessage("保存数据异常。");
      return _result;
    }

    TsCode _model = TsCode.dao.findById(model.getId());

    if(_model == null) {
      _result.setState(ContextStateEnum.FAIL);
      _result.setMessage("数据不存在，或已被删除。");
      return _result;
    }

    String _customid = model.getCustomid();
    TsCode _exsitName = TsCode.dao.findFirst("SELECT * FROM TS_CODE \n" +
                                               " WHERE ID<>? AND (((CUSTOMID =? OR CODENAME =?) AND LEAF = '0') OR \n" +
                                               " (( CUSTOMID =? OR (CODENAME =? AND PARENTCUSTOMID =?)) AND CODETYPE =?) OR \n" +
                                               " (LEAF='1' AND CUSTOMID=? ))",
                                             model.getId(), _customid,model.getCodename(), _customid, model.getCodename(),
                                             model.getParentcustomid(), model.getCodeType(),_customid);
    if(_exsitName != null) {
      if(model.getParentcustomid()==null && _exsitName.getParentcustomid()==null && _exsitName.getLeaf().equals(model.getLeaf()))      {
        if(_exsitName.getCodename().equals(model.getCodename())) {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下名称已经存在。");
        } else {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下自定义编号已经存在。");
        }
      }else if(_exsitName.getLeaf().equals(model.getLeaf()) && model.getParentcustomid().equals(_exsitName.getParentcustomid())) {
        if(_exsitName.getCodename().equals(model.getCodename())) {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下名称已经存在。");
        } else if(_exsitName.getCustomid().equals(model.getCustomid())) {
          _result.setState(ContextStateEnum.FAIL);
          _result.setMessage("同级下自定义编号已经存在。");
        }
      } else if("1".equals(_exsitName.getLeaf())) {
        _result.setState(ContextStateEnum.FAIL);
        _result.setMessage("自定义编号不能与1级节点相同。");
      } else if("0".equals(_exsitName.getLeaf())) {
        _result.setState(ContextStateEnum.FAIL);
        _result.setMessage("自定义编号不能与根节点相同。");
      } else {
        _result.setState(ContextStateEnum.FAIL);
        _result.setMessage("当前1级节点下自定义编号已经存在。");
      }
      return _result;
    }

    if("null".equals(model.getIcon())){
      model.setIcon("");
    }


    List<String> _strSql = new ArrayList<String>();


    _strSql.add(String.format("UPDATE TS_CODE SET CODENAME='%s',CUSTOMID='%s',SORTNO=%s,REMARK='%s',SPECIALID='%s',icon='%s' WHERE ID='%s'", model.getCodename(), model.getCustomid(), model.getSortno(), model.getRemark() == null ? "" : model.getRemark(),model.getSpecialid() == null ? "" : model.getSpecialid(),model.getIcon() == null ? "" : model.getIcon(), model.getId()));

    _strSql.add(String.format("UPDATE TS_CODE SET PARENTNAME='%s',PARENTCUSTOMID='%s' WHERE PARENTID='%s'", model.getCodename(),model.getCustomid() ,model.getCodeid()));

    if("1".equals(_model.getLeaf())){
      _strSql.add(String.format("UPDATE TS_CODE SET CODETYPE='%s' WHERE SUBSTR(CODEID, 1, 6) = '%S' AND LEAF != '0' ", model.getCustomid() ,model.getCodeid()));
    }
    //_strSql.add(String.format("UPDATE TS_CODE SET PARENTNAME='%s' WHERE PARENTID='%s'", model.getCodename(),model.getCodeid()));
    Db.batch(_strSql, 10000);
    _result.setState(ContextStateEnum.SUCCESS);
    log(user.getLoginId(), user.getName(), "系统管理/数据词典", "修改", user.getIp(), "主键：" + model.getId() + "，名称：" + model.getCodename() + "，编号：" + model.getCodeid());
    _result.setMessage("保存成功。");
    return _result;
  }

  /**
  * @MethodName: removeCodes
  * @Description: 删除信息，删除时会将子集全部删除
  * @param: codeids
   * @param: user
  * @return * @return int
  * @throws
  * @date 2023/8/31 12:37
  * @author wj
  */
  @Before(Tx.class)
  public int removeCodes(String[] codeids,Authuser user) {

    List<String> _sqlList = new ArrayList<String>();

    for(int i = 0; i < codeids.length; i++) {
      pushRemoveSQL(codeids[i], _sqlList,user);
    }

    Db.batch(_sqlList, 10000);
    return 0;
  }

  /**
  * @MethodName: pushRemoveSQL
  * @Description: 拼接删除SQL
  * @param: codeid
   * @param: sqlList
   * @param: user
  * @return * @return void
  * @throws
  * @date 2023/8/31 12:38
  * @author wj
  */
  public void pushRemoveSQL(String codeid, List<String> sqlList,Authuser user) {

    List<TsCode> _childdata = TsCode.dao.find("SELECT * FROM TS_CODE WHERE PARENTID=?", codeid);
    List<TsCode> _parentData = TsCode.dao.find("SELECT * FROM TS_CODE WHERE CODEID=?", codeid);
    if(_parentData!=null&&_parentData.size()>0){
      sqlList.add(String.format("DELETE FROM TS_CODE WHERE CODEID = '%s'", codeid));
       log(user.getLoginId(), user.getName(), "系统管理/数据词典", "删除", user.getIp(), "主键：" + _parentData.get(0).getId() + "，名称：" + _parentData.get(0).getCodename() + "，编号：" + codeid);
    }

    if(_childdata != null && _childdata.size() > 0) {
      for(TsCode t : _childdata) {
        sqlList.add(String.format("DELETE FROM TS_CODE WHERE CODEID = '%s'", t.getCodeid()));
        log(user.getLoginId(), user.getName(), "系统管理/数据词典", "删除", user.getIp(), "主键：" + t.getId() + "，名称：" + t.getCodename() + "，编号：" + t.getCodeid());
        pushRemoveSQL(t.getCodeid(), sqlList,user);
      }
    }
  }

  public String doTest(String hqlAes) throws Exception {

    Map<String, Object> params = new HashMap();
    params.put("content",hqlAes);

    String jsonResult = HttpKit.post("http://10.114.1.23:30080/lpapi/doTest", JsonUtils.toJson(params));

    return jsonResult;
  }

  /**
  * @MethodName: changeState
  * @Description: 启用择需要判断父级是否被禁用，如父级被禁用，则不允许启用
  * @param: codeids 禁用将子集全部一起禁用
   * @param: state 修改状态，启用，禁用
   * @param: user
  * @return * @return int
  * @throws
  * @date 2023/8/31 12:39
  * @author wj
  */
  @Before(Tx.class)
  public int changeState(String[] codeids, StateEnumCls state,Authuser user) {

    List<String> _sqlList = new ArrayList<String>();
    int _result = 0;
    if(state == StateEnumCls.ENABLED) {
      for(int i = 0; i < codeids.length; i++) {
        _result = validationWhetherAllowChangeState(codeids[i]);
      }
    }

    if(_result == -1) {
      return _result;
    }
    for(int i = 0; i < codeids.length; i++) {
      pushchangeStateSQL(codeids[i], _sqlList, state,user);
    }
    Db.batch(_sqlList, 10000);

    return _result;
  }

  /**
  * @MethodName: pushchangeStateSQL
  * @Description: 拼接修改状态SQL
  * @param: codeid
   * @param: sqlList
   * @param: state
   * @param: user
  * @return * @return void
  * @throws
  * @date 2023/8/31 12:40
  * @author wj
  */
  public void pushchangeStateSQL(String codeid, List<String> sqlList, StateEnumCls state,Authuser user) {

    List<TsCode> _childdata = TsCode.dao.find("SELECT * FROM TS_CODE WHERE PARENTID=?", codeid);
    List<TsCode> _parentData = TsCode.dao.find("SELECT * FROM TS_CODE WHERE CODEID=?", codeid);
    if(_parentData!=null&&_parentData.size()>0){
      sqlList.add(String.format("UPDATE TS_CODE SET ENABLED='%s' WHERE CODEID = '%s'", state.getValue(), codeid));
      log(user.getLoginId(), user.getName(), "系统管理/数据词典", "启用/禁用", user.getIp(), "主键：" + _parentData.get(0).getId() + "，名称：" + _parentData.get(0).getCodename() + "，编号：" + codeid+",状态值："+state.getValue());
    }

    if(_childdata != null && _childdata.size() > 0) {
      for(TsCode t : _childdata) {
        sqlList.add(String.format("UPDATE TS_CODE SET ENABLED='%s' WHERE CODEID = '%s'", state.getValue(), t.getCodeid()));
        log(user.getLoginId(), user.getName(), "系统管理/数据词典", "启用/禁用", user.getIp(), "主键：" + t.getId() + "，名称：" + t.getCodename() + "，编号：" + t.getCodeid()+",状态值："+state.getValue());
        pushchangeStateSQL(t.getCodeid(), sqlList, state,user);
      }
    }

  }

  /**
  * @MethodName: validationWhetherAllowChangeState
  * @Description: 验证父级节点是否有被禁用
  * @param: codeid
  * @return * @return int
  * @throws
  * @date 2023/8/31 12:41
  * @author wj
  */
  public int validationWhetherAllowChangeState(String codeid) {
    TsCode _parentdata = TsCode.dao.findFirst("SELECT * FROM TS_CODE WHERE CODEID=(SELECT PARENTID FROM TS_CODE WHERE CODEID=?)", codeid);

    if(_parentdata != null) {
      if(_parentdata.getEnabled().equals(StateEnumCls.DISABLED.getValue())) {
        return -1;
      } else {
        int _r = validationWhetherAllowChangeState(_parentdata.getCodeid());
        if(_r == -1) {
          return -1;
        }
      }
    }
    return 0;
  }

  /**
  * @MethodName: exportCodes
  * @Description: 导出信息SQL
  * @param: parentId
   * @param: codeName
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:41
  * @author wj
  */
  public List<TsCode> exportCodes(String parentId, String codeName) {
    StringBuilder _strsql = new StringBuilder();
    _strsql.append("SELECT  ID,\n" +
                     "        CODEID,\n" +
                     "        CODENAME,\n" +
                     "        CUSTOMID,\n" +
                     "        SPECIALID,\n" +
                     "        MODIFICATION_NUM,\n" +
                     "        PARENTID,\n" +
                     "        PARENTNAME,\n" +
                     "        LEAF,\n" +
                     "        REMARK,\n" +
                     "        CASE ENABLED WHEN '1' THEN '启用' ELSE '禁用' END  ENABLED_CN,\n" +
                     "        SORTNO,\n" +
                     "        CREATED FROM TS_CODE WHERE 1=1 ");

    List<String> _where = new ArrayList<String>();

    if(StrKit.hasValue(parentId)) {
      _strsql.append(" AND PARENTID=?");
      _where.add(parentId);

      if(StrKit.hasValue(codeName)) {
        _strsql.append(" AND CODENAME LIKE '%?%' ");
        _where.add(codeName);
      }
    }

    _strsql.append(" ORDER BY SORTNO ASC");

    List<TsCode> _returnData = TsCode.dao.find(_strsql.toString(), _where.toArray());

    return _returnData;
  }

  /**
  * @MethodName: getCodeAllNodesByParentName
  * @Description: 根据父级Name获取所有子集的数据返回集合，集合不形成层级关系
  * @param: parentName
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:42
  * @author wj
  */
  public List<TsCode> getCodeAllNodesByParentName(String parentName) {

    List<TsCode> _returnList = TsCode.dao.find("SELECT * FROM TS_CODE WHERE ENABLED = 1 AND  ROOTCUSTOMID = 'BUSINESS' ORDER BY SORTNO ASC,CODEID ASC");

    return _returnList;
  }

  /**
  * @MethodName: getCodesByParentCustomId
  * @Description: 根据父级CustomId获取下一集子集的数据返回集合
  * @param: parentCustomId
   * @param: codeType
   * @param: isEnabled 启用，禁用
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:42
  * @author wj
  */
  public List<TsCode> getCodesByParentCustomId(String parentCustomId, String codeType,String isEnabled) {

    List<TsCode> _returnList = TsCode.dao.find("SELECT * FROM TS_CODE WHERE PARENTCUSTOMID = ? AND CODETYPE = ? AND ENABLED = ? AND  ROOTCUSTOMID = 'BUSINESS' ORDER BY SORTNO ASC,CODEID ASC",
                                               parentCustomId, codeType, isEnabled);
    return _returnList;
  }

  /**
  * @MethodName: getCodesByParentCustomId
  * @Description: 根据父级CustomId获取下一集子集的数据返回集合
  * @param: parentCustomId
   * @param: codeType
   * @param: isEnabled:启用，禁用
   * @param: rootCustomId
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:43
  * @author wj
  */
  public List<TsCode> getCodesByParentCustomId(String parentCustomId, String codeType,String isEnabled,String rootCustomId) {

    List<TsCode> _returnList = TsCode.dao.find("SELECT * FROM TS_CODE WHERE PARENTCUSTOMID = ? AND CODETYPE = ? AND ENABLED = ? AND ROOTCUSTOMID=? ORDER BY SORTNO ASC,CODEID ASC",
                                               parentCustomId, codeType, isEnabled,rootCustomId);
    return _returnList;
  }


  /**
  * @MethodName: getCodesByParentCustomId
  * @Description: 根据父级CustomId获取下一集子集的数据返回集合
   * @param: leaf
   * @param: codeType
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:44
  * @author wj
  */
  public List<TsCode> getCodesByParentCustomId(String leaf, String codeType) {

    List<TsCode> _returnList = TsCode.dao.find("SELECT * FROM TS_CODE WHERE LEAF = ? AND CODETYPE = ? AND ENABLED = 1  ORDER BY SORTNO ASC,CODEID ASC",
                                               leaf, codeType.toUpperCase());
    return _returnList;
  }



  /**
  * @MethodName: getCodesByCodeTypeAndLeaf
  * @Description: 根据codetype和叶节点获取业务代码的数据返回集合
  * @param: leaf
   * @param: codeType
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:45
  * @author wj
  */
  public List<TsCode> getCodesByCodeTypeAndLeaf(String leaf, String codeType) {
    return getCodesByCodeTypeAndLeaf(leaf,codeType,"","");
  }

  public List<TsCode> getCodesByCodeTypeAndLeaf(String leaf, String codeType,String searchName, String pcode) {


    String _sql = "";
    List<TsCode> _returnList = new ArrayList<TsCode>();
    if(StrKit.notBlank(searchName)){

      if(StrKit.notBlank(pcode)){
        _sql = "SELECT * FROM TS_CODE WHERE LEAF = ? AND CODETYPE = ? AND PARENTCUSTOMID = ? AND ENABLED = 1  AND  ROOTCUSTOMID = 'BUSINESS' AND CODENAME LIKE '%"+searchName+"'%' ORDER BY SORTNO ASC,CODEID ASC";
        _returnList = TsCode.dao.find(_sql,leaf, codeType,pcode);
      }else{
        _sql = "SELECT * FROM TS_CODE WHERE LEAF = ? AND CODETYPE = ? AND ENABLED = 1  AND  ROOTCUSTOMID = 'BUSINESS' AND CODENAME LIKE '%"+searchName+"'%' ORDER BY SORTNO ASC,CODEID ASC";
        _returnList = TsCode.dao.find(_sql,leaf, codeType);
      }
    }else{

      if(StrKit.notBlank(pcode)){
        _sql = "SELECT * FROM TS_CODE WHERE LEAF = ? AND CODETYPE = ? AND PARENTCUSTOMID = ? AND ENABLED = 1  AND  ROOTCUSTOMID = 'BUSINESS' ORDER BY SORTNO ASC,CODEID ASC";
        _returnList = TsCode.dao.find(_sql,leaf, codeType, pcode);
      }else{
        _sql = "SELECT * FROM TS_CODE WHERE LEAF = ? AND CODETYPE = ? AND ENABLED = 1  AND  ROOTCUSTOMID = 'BUSINESS' ORDER BY SORTNO ASC,CODEID ASC";
        _returnList = TsCode.dao.find(_sql,leaf, codeType);
      }

    }



    return _returnList;
  }



  /**
  * @MethodName: getCodesByParentCustomId
  * @Description: 根据父级CustomId获取下一集子集的数据返回集合
  * @param: parentCustomId
   * @param: codeType
   * @param: choose
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:45
  * @author wj
  */
  public List<TsCode> getCodesByParentCustomId(String parentCustomId, String codeType, boolean choose) {

    List<TsCode> _returnList = TsCode.dao.find("SELECT * FROM TS_CODE WHERE PARENTCUSTOMID = ? AND CODETYPE = ? AND ENABLED = 1 ORDER BY SORTNO ASC,CODEID ASC",
                                               parentCustomId, codeType);
    if(choose) {
      TsCode _choose = new TsCode();
      _choose.setCustomid("");
      _choose.setCodename("请选择");
      _returnList.add(0, _choose);
    }

    return _returnList;
  }

  /**
  * @MethodName: getCodeByCustomid
  * @Description: 获取code
  * @param: codeType
   * @param: customid
  * @return * @return net.yxsoft.model.infrastructure.TsCode
  * @throws
  * @date 2023/8/31 12:46
  * @author wj
  */
  public TsCode getCodeByCustomid(String codeType,String customid) {
    TsCode _retsult = TsCode.dao.findFirst("select * from ts_code where codetype=? and customid=? and enabled='1'",codeType,customid);
    return _retsult;
  }



  /**
  * @MethodName: getCodeTopNodes
  * @Description: 获取1级节点
  * @param:
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:46
  * @author wj
  */
  public List<TsCode> getCodeTopNodes() {
    List<TsCode> _returnList = TsCode.dao.find("select * from ts_code where rootcustomid='BUSINESS' and leaf = '1' and enabled='1'");
    return _returnList;
  }

  /**
  * @MethodName: getCodeAllNodesByCodeType
  * @Description: 获取某个1级下所有节点(true包含1级节点,false不包含1级节点)
  * @param: codeType
   * @param: isContains
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:46
  * @author wj
  */
  public List<TsCode> getCodeAllNodesByCodeType(String codeType, boolean isContains) {
    StringBuilder _strsql = new StringBuilder();
    _strsql.append("select * from ts_code where codeType = ? and rootcustomid='BUSINESS' and enabled='1'");
    if(!isContains) {
      _strsql.append(" and leaf!='1' ");
    }
    List<TsCode> _returnList = TsCode.dao.find(_strsql.toString(), codeType);
    return _returnList;
  }

  /**
  * @MethodName: getCodeAllNodes
  * @Description: 获取除0、1两级的所有节点
  * @param:
  * @return * @return java.util.List<net.yxsoft.model.infrastructure.TsCode>
  * @throws
  * @date 2023/8/31 12:46
  * @author wj
  */
  public List<TsCode> getCodeAllNodes() {
    List<TsCode> _returnList = TsCode.dao.find("select * from ts_code where rootcustomid='BUSINESS' and leaf not in ('0','1') and enabled='1'");
    return _returnList;
  }

/**
* @MethodName: getCodeTopInfo
* @Description: 获取一级数据
* @param:
* @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
* @throws
* @date 2023/8/31 12:47
* @author wj
*/
  public List<Record> getCodeTopInfo() {
    if(DbSourceRes.DB_SOURCE_MYSQL.equals(PropKit.get("dbType"))) {
      return Db.find("select codename as text,concat_ws('|',codename,customid,codetype) as value from ts_code where rootcustomid='BUSINESS' and leaf = '1' and enabled='1' order by sortno");
    }else{
      return Db.find("select codename as text,codename || '|' || customid || '|' || codetype as value from ts_code where rootcustomid='BUSINESS' and leaf = '1' and enabled='1' order by sortno");
    }

  }
  /**
  * @MethodName: getCodeByParam
  * @Description: 获取数据字典数据
  * @param: rootCustId
   * @param: oneCodeid
   * @param: leaf
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 12:47
  * @author wj
  */
  public List<Record> getCodeByParam(String rootCustId, String oneCodeid, String leaf) {
    return Db.find("select codename text,customid value from ts_code where rootcustomid=? and codetype=? and leaf=? and enabled='1' order by sortno", rootCustId, oneCodeid, leaf);
  }

  public static final String codeCache = "powerTscode";  //万能导入缓存

  /**
  * @MethodName: removeCodeCache
  * @Description: 清除缓存
  * @param:
  * @return * @return void
  * @throws
  * @date 2023/8/31 12:48
  * @author wj
  */
  private void removeCodeCache() {
    CacheKit.removeAll(codeCache);
  }

  /**
  * @MethodName: getTsCodeByCodeTypeAndLeaf
  * @Description: 万能导入获取数据字典数据
  * @param: rootcustomid
   * @param: codetype
   * @param: leaf
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 12:48
  * @author wj
  */
  public List<Record> getTsCodeByCodeTypeAndLeaf(String rootcustomid, String codetype, String leaf) {
    return Db.findByCache(codeCache, rootcustomid + "_" + codetype + "_" + leaf + "_powerImport", "select a.*,'code' as tag from ts_code a where a.rootcustomid=? and a.codetype=? and a.leaf=? and a.enabled='1'", rootcustomid, codetype, leaf);
  }
}
